<?php
namespace Manage\Controller;


use Think\Controller;


class BaseController extends Controller {
    protected $_arr;
    public $page_num;
    public function __construct(){
        parent::__construct();
        $this->page_num = C('PAGE_NUM');
        $this->isLogin();
        $menu = $this->power();
        $nav_menu=$this->navMenu(); // 左侧菜单
        $this->assign(['menu' => $menu,'nav_menu' => $nav_menu]);
    }

    /**
     * 重写display
     * @param string $string
     */
    public function _showDisplay($string='') {
        $this->assign($this->_arr);
        $this->display($string);
    }

    /**
     * 判断是否登陆
     */
    public function isLogin(){
        $manageInfo = session('manageInfo');
        if (empty($manageInfo)) {
            $this->redirect('/manage/login/index');
        }
    }
    /**
     * 判断用户权限
     */
    public function power(){
        $manageInfo = session('manageInfo');
//        echo $manageInfo['login_name'];exit;
        if ($manageInfo['login_name'] != 'admin') {

            // 查询角色信息
            $userRole = M('manage_user_role');
            $roleMsg = $userRole->where(['manege_id' => $manageInfo['account_id']])->find();

            $roleMenu = M('b2c_manage_role_menu');
            // 角色左链接查询菜单信息
            $sql = "select b.* from sdb_b2c_manage_role_menu a LEFT JOIN sdb_b2c_manage_menu b on a.menu_id = b.id WHERE a.role_id =  $roleMsg[role_id]";
            $roleMenuMsg = $roleMenu->query($sql);
//            echo $roleMenu->_sql();
//var_dump($roleMenuMsg);exit;
            // 判断是否有权限，权限到控制器
            $variable = false;
            foreach ($roleMenuMsg as $v) {
                if ($v['group'] == MODULE_NAME && $v['controller'] == CONTROLLER_NAME) {
                    $variable = true;
                }
            }

            if ($variable === false) {
                $this->error('没有权限');
            }
            return $roleMenuMsg;
        }
    }
    public function navMenu(){
        $manageInfo = session('manageInfo');
        if ($manageInfo['login_name'] != 'admin') {

            // 查询角色信息
            $userRole = M('manage_user_role');
            $roleMsg = $userRole->where(['manege_id' => $manageInfo['account_id']])->find(); // 查询角色id

            $roleMenu = M('b2c_manage_role_menu');
            // 角色左链接查询菜单信息
            $sql = "select b.* from sdb_b2c_manage_role_menu a LEFT JOIN sdb_b2c_manage_menu b on a.menu_id = b.id WHERE a.role_id =  $roleMsg[role_id] GROUP BY b.nav_menu_id";
            $roleMenuMsg = $roleMenu->query($sql);
            for ($i =0; $i<count($roleMenuMsg); $i ++ ) {
                $m = M('b2c_manage_nav_menu');
                $nav_menu[] = $m->where(['id' => $roleMenuMsg[$i]['nav_menu_id']])->find();
            }
            return $nav_menu;
        }
    }


}